package com.yubb.web.controller.platform;

import com.yubb.common.annotation.PlatformLog;
import com.yubb.common.constant.UserConstants;
import com.yubb.common.core.controller.BaseController;
import com.yubb.common.core.domain.AjaxResult;
import com.yubb.common.core.domain.platform.dto.PlatformRoleDTO;
import com.yubb.common.core.domain.platform.dto.PlatformUserDTO;
import com.yubb.common.core.domain.platform.vo.PlatformRoleVO;
import com.yubb.common.core.domain.platform.vo.PlatformUserVO;
import com.yubb.common.core.page.TableDataInfo;
import com.yubb.common.enums.BusinessType;
import com.yubb.common.utils.ShiroUtils;
import com.yubb.common.utils.poi.ExcelUtil;
import com.yubb.framework.shiro.util.AuthorizationUtils;
import com.yubb.platform.domain.PlatformUserRole;
import com.yubb.platform.service.IPlatformRoleService;
import com.yubb.platform.service.IPlatformUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *@Description 角色信息
 *@Author zhushuyong
 *@Date 2021/5/26 14:44
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Controller
@RequestMapping("/platform/role")
public class PlatformRoleController extends BaseController
{
    private String prefix = "platform/role";

    @Autowired
    private IPlatformRoleService roleService;

    @Autowired
    private IPlatformUserService userService;

    @RequiresPermissions("platform:role:view")
    @GetMapping()
    public String role()
    {
        return prefix + "/role";
    }

    @RequiresPermissions("platform:role:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PlatformRoleDTO role) {
        startPage();
        List<PlatformRoleVO> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @PlatformLog(title = "角色管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("platform:role:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PlatformRoleDTO role) {
        List<PlatformRoleVO> list = roleService.selectRoleList(role);
        ExcelUtil<PlatformRoleVO> util = new ExcelUtil<PlatformRoleVO>(PlatformRoleVO.class);
        return util.exportExcel(list, "角色数据");
    }

    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存角色
     */
    @RequiresPermissions("platform:role:add")
    @PlatformLog(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated PlatformRoleDTO role) {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(ShiroUtils.getPlatformUser().getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改角色
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/edit";
    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("platform:role:edit")
    @PlatformLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated PlatformRoleDTO role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(ShiroUtils.getPlatformUser().getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 角色分配数据权限
     */
    @GetMapping("/authDataScope/{id}")
    public String authDataScope(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/dataScope";
    }

    /**
     * 保存角色分配数据权限
     */
    @RequiresPermissions("platform:role:edit")
    @PlatformLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/authDataScope")
    @ResponseBody
    public AjaxResult authDataScopeSave(PlatformRoleDTO role)
    {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(ShiroUtils.getPlatformUser().getLoginName());
        if (roleService.authDataScope(role)) {
            PlatformUserVO platformUserVO = userService.selectUserById(ShiroUtils.getPlatformUser().getId());
            ShiroUtils.setPlatformUser(platformUserVO);
            return success();
        }
        return error();
    }

    @RequiresPermissions("platform:role:remove")
    @PlatformLog(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(roleService.deleteRoleByIds(ids));
    }

    /**
     * 校验角色名称
     */
    @PostMapping("/checkRoleNameUnique")
    @ResponseBody
    public String checkRoleNameUnique(PlatformRoleDTO role)
    {
        return roleService.checkRoleNameUnique(role);
    }

    /**
     * 校验角色权限
     */
    @PostMapping("/checkRoleKeyUnique")
    @ResponseBody
    public String checkRoleKeyUnique(PlatformRoleDTO role)
    {
        return roleService.checkRoleKeyUnique(role);
    }

    /**
     * 角色状态修改
     */
    @PlatformLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("platform:role:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(PlatformRoleDTO role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.changeStatus(role));
    }

    /**
     * 分配用户
     */
    @RequiresPermissions("platform:role:edit")
    @GetMapping("/authUser/{id}")
    public String authUser(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/authUser";
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("platform:role:list")
    @PostMapping("/authUser/allocatedList")
    @ResponseBody
    public TableDataInfo allocatedList(PlatformUserDTO user)
    {
        startPage();
        List<PlatformUserVO> list = userService.selectAllocatedList(user);
        return getDataTable(list);
    }

    /**
     * 取消授权
     */
    @PlatformLog(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancel")
    @ResponseBody
    public AjaxResult cancelAuthUser(PlatformUserRole userRole) {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权
     */
    @PlatformLog(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancelAll")
    @ResponseBody
    public AjaxResult cancelAuthUserAll(String roleId, String userIds) {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 选择用户
     */
    @GetMapping("/authUser/selectUser/{id}")
    public String selectUser(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/selectUser";
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("platform:role:list")
    @PostMapping("/authUser/unallocatedList")
    @ResponseBody
    public TableDataInfo unallocatedList(PlatformUserDTO user)
    {
        startPage();
        List<PlatformUserVO> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 批量选择用户授权
     */
    @PlatformLog(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/selectAll")
    @ResponseBody
    public AjaxResult selectAuthUserAll(String roleId, String userIds) {
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }
}